<script setup>
import api from '../api/userApi.js'
import { ref, onMounted } from 'vue'
import {
  ElMessage,
  ElMessageBox,
  ElDialog,
  ElNotification,
  ElTable,
  ElTableColumn,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElPagination,
  ElTag,
  ElSelect,
  ElOption,
  ElImage,
  ElUpload
} from 'element-plus'
import { Delete, Edit, Search } from '@element-plus/icons-vue'
import lodash from 'lodash'

// 表格数据
const tableData = ref([])
// 总记录数
const total = ref(0)
// 编辑/新增弹窗显隐
const updateWinVisible = ref(false)
// 表单绑定数据
const obj = ref({})

// 查询参数（分页 + 搜索条件）
const searchObj = ref({
  page: 1,
  pageSize: 10,
  username: '', // 用户名搜索
  isdel: 0
})

// 查询数据方法（根据实际API响应结构优化）
const search = async () => {
  try {
    const result = await api.page(searchObj.value)
    console.log('接口完整响应:', result)

    // 根据实际API响应结构处理数据
    if (result && result.records && Array.isArray(result.records)) {
      tableData.value = result.records
      total.value = result.total || 0
      console.log('表格数据:', tableData.value)
      console.log('总记录数:', total.value)
    } else {
      tableData.value = []
      total.value = 0
      console.warn('API响应格式异常:', result)
    }
  } catch (error) {
    ElMessage.error('查询失败，请检查网络或接口！')
    console.error('查询错误详情:', error)
    tableData.value = []
    total.value = 0
  }
}

// 页面挂载时初始化数据
onMounted(async () => {
  await search()
})

// 编辑功能（深拷贝避免原数据被修改）
const handleEdit = (index, row) => {
  obj.value = lodash.cloneDeep(row)
  updateWinVisible.value = true
}

// 删除功能（带二次确认）
const handleDelete = async (index, row) => {
  ElMessageBox.confirm(
      '确定删除该管理员吗？删除后不可恢复！',
      '危险操作',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'danger'
      }
  )
      .then(async () => {
        try {
          await api.delete(row.id)
          ElMessage.success('删除成功！')
          await search() // 重新加载当前页
        } catch (error) {
          ElMessage.error('删除失败：' + (error.response?.data?.msg || '接口异常'))
          console.error('删除错误详情:', error)
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
}

// 保存编辑/新增（区分新增和编辑）
const handleSave = async () => {
  try {
    if (obj.value.id) {
      // 编辑操作
      await api.update(obj.value)
      ElMessage.success('更新成功！')
    } else {
      // 新增操作
      await api.add(obj.value)
      ElMessage.success('新增成功！')
    }
    updateWinVisible.value = false
    await search() // 刷新表格
    obj.value = {} // 清空表单
  } catch (error) {
    ElMessage.error('操作失败：' + (error.response?.data?.msg || '接口异常'))
    console.error('保存错误详情:', error)
  }
}

// 取消编辑（清空表单 + 关闭弹窗）
const handleCancel = () => {
  updateWinVisible.value = false
  obj.value = {}
}

// 新增管理员（清空表单 + 打开弹窗）
const handleAdd = () => {
  obj.value = {}
  updateWinVisible.value = true
}

// 分页大小改变（如从10条/页 → 20条/页）
const handleSizeChange = async (newSize) => {
  searchObj.value.pageSize = newSize
  searchObj.value.page = 1 // 重置到第一页
  await search()
}

// 当前页改变（如从第1页 → 第2页）
const handleCurrentChange = async (newPage) => {
  searchObj.value.page = newPage
  await search()
}

// 搜索按钮（带分页重置）
const handleSearch = async () => {
  searchObj.value.page = 1 // 搜索时默认查第一页
  await search()
}

// 重置搜索条件（清空搜索框 + 分页重置）
const handleReset = async () => {
  searchObj.value = {
    page: 1,
    pageSize: 10,
    username: '',
    isDel: 0
  }
  await search()
}

const formatGender = (gender) => {
  const genderMap = {1: '男', 2: '女'};
  return genderMap[gender] || '未填写';
};

const formatTime = (timeStr) => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  // 格式化为：年-月-日 时:分:秒
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
};

// 4. 通知组件
const showNotification = (options) => {
  const {type, message} = options;
  if (!type || !message) {
    console.warn('通知类型和消息内容不能为空');
    return;
  }

  ElNotification({
    title: type === 'success' ? '成功' :
        type === 'error' ? '错误' :
            type === 'warning' ? '警告' : '信息',
    message: message,
    type: type,
    duration: 2000
  })
}

// 图片上传处理
const handleUploadSuccess = (response, file) => {
  console.log('上传响应:', response); // 添加调试日志
  
  // 检查响应状态码
  if (response.code === 200) {
    obj.value.image = response.data;
    showNotification({type: 'success', message: '图片上传成功'});
  } else {
    showNotification({
      type: 'error',
      message: '图片上传失败: ' + (response.msg || response.message || '未知错误')
    });
  }
}

const handleUploadError = (error) => {
  showNotification({
    type: 'error',
    message: '上传失败: ' + (error.message || '网络错误')
  });
}
</script>

<template>
  <div class="page-container">
    <!-- 搜索 + 按钮区域 -->
    <div class="top-bar">
      <!-- 搜索区域 -->
      <el-form :model="searchObj" inline class="search-form">
        <el-form-item label="用户名：">
          <el-input
              v-model="searchObj.username"
              placeholder="请输入用户名"
              clearable
              style="width: 200px;"
          />
        </el-form-item>
        <el-form-item label="账号状态:">
          <el-select
              v-model="searchObj.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px;"
              @change="handleSearch"
          >
            <el-option label="全部" :value="null"></el-option>
            <el-option label="正常" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别:">
          <el-select
              v-model="searchObj.gender"
              placeholder="请选择性别"
              clearable
              style="width: 150px;"
              @change="handleSearch"
          >
            <el-option label="全部" :value="null"></el-option>
            <el-option label="男" :value="1"></el-option>
            <el-option label="女" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" circle @click="handleSearch" />
          <el-button type="default" :icon="Delete" circle @click="handleReset" />
        </el-form-item>
      </el-form>

      <!-- 新增按钮（右对齐） -->
      <el-button type="success" round @click="handleAdd" class="add-btn">新增管理员</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
          :data="tableData"
          class="user-table"
          border
          stripe
          empty-text="暂无数据"
          v-loading="false"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
      >
        <el-table-column fixed prop="id" label="ID" width="80" align="center" />
        <el-table-column label="头像" width="120" align="center">
          <template #default="scope">
            <el-image
                v-if="scope.row.image"
                style="width: 60px; height: 60px; cursor: pointer"
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
                fit="cover"
            />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" min-width="120" show-overflow-tooltip />
        <el-table-column prop="phone" label="手机号" min-width="140" show-overflow-tooltip />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            <el-tag
                :type="scope.row.gender === 1 ? 'primary' : scope.row.gender === 2 ? 'danger' : 'info'"
                size="small"
            >
              {{ formatGender(scope.row.gender) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.createtime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150" align="center">
          <template #default="scope">
            <el-button
                type="primary"
                :icon="Edit"
                circle
                size="small"
                @click="handleEdit(scope.$index, scope.row)"
                title="编辑"
            />
            <el-button
                type="danger"
                :icon="Delete"
                circle
                size="small"
                @click="handleDelete(scope.$index, scope.row)"
                title="删除"
                style="margin-left: 8px;"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="searchObj.page"
          v-model:page-size="searchObj.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑/新增弹窗 -->
    <el-dialog
        v-model="updateWinVisible"
        :title="obj.id ? '编辑管理员' : '新增管理员'"
        width="500px"
        :before-close="handleCancel"
    >
      <el-form :model="obj" label-width="100px" style="margin-top: 20px;">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="obj.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" v-if="!obj.id">
          <el-input
              v-model="obj.password"
              type="password"
              placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="obj.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="obj.gender" placeholder="请选择性别" style="width: 100%">
            <el-option label="男" :value="1"/>
            <el-option label="女" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="账号状态" prop="status">
          <el-select v-model="obj.status" placeholder="请选择状态">
            <el-option label="正常" :value="1"/>
            <el-option label="禁用" :value="0"/>
          </el-select>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
              class="avatar-uploader"
              action="/api/Upload/toUpload"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="(file) => {
              const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
              if (!isJpgOrPng) {
                showNotification({ type: 'error', message: '请上传JPG或PNG格式的图片' });
                return false;
              }
              const isLt2M = file.size / 1024 / 1024 < 2;
              if (!isLt2M) {
                showNotification({ type: 'error', message: '图片大小不能超过2MB' });
                return false;
              }
              return true;
            }"
          >
            <img
                :src="obj.image ? obj.image : 'src/assets/111.jpg'"
                style="width: 100px; height: 100px"
                class="avatar"
                alt="用户头像"
            />
          </el-upload>
          <div style="margin-top: 8px; font-size: 12px; color: #999;">点击图片上传头像</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 页面整体容器 */
.page-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
}

/* 顶部搜索 + 按钮栏 */
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 搜索表单 */
.search-form {
  display: flex;
  align-items: center;
}

/* 新增按钮 */
.add-btn {
  padding: 8px 20px; /* 缩小按钮内边距，避免过宽 */
  font-size: 14px;
}

/* 表格容器 */
.table-container {
  width: 100%;
  overflow-x: auto;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

/* 头像上传样式 */
.avatar-uploader {
  display: flex;
  justify-content: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

/* 头像样式 */
.avatar {
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px dashed #ddd;
}

.avatar:hover {
  opacity: 0.9;
  transform: scale(1.02);
}

/* 表格样式 */
.user-table {
  width: 100%;
  min-width: 800px;
}

/* 表格行悬停 */
:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 表格头部 */
:deep(.el-table th.el-table__cell) {
  padding: 12px 0;
  font-size: 14px;
}

/* 表格单元格 */
:deep(.el-table td.el-table__cell) {
  padding: 10px 0;
}

/* 分页容器 */
.pagination-container {
  text-align: center;
  margin-top: 20px;
}

/* 按钮间距 */
.el-button + .el-button {
  margin-left: 10px;
}

/* 弹窗内容滚动 */
:deep(.el-dialog__body) {
  max-height: 60vh;
  overflow-y: auto;
}

/* 响应式适配（小屏幕） */
@media (max-width: 768px) {
  .page-container {
    padding: 10px;
  }
  .top-bar {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px; /* 按钮与搜索框间距 */
  }
  .search-form {
    width: 100%;
  }
  .add-btn {
    align-self: flex-start; /* 按钮左对齐 */
  }
  .table-container {
    margin: 10px 0;
    border-radius: 4px;
  }
  :deep(.el-table th.el-table__cell),
  :deep(.el-table td.el-table__cell) {
    padding: 8px 0;
    font-size: 12px;
  }
}
</style>